package com.learn.mvc.utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import com.learn.mvc.pojo.ConfigBean;

public class StrutsConfig {
	static Map<String, ConfigBean> xmlBeanMap = new HashMap<String, ConfigBean>();

	public static Map<String, ConfigBean> getXmlBeanMap() {
		return xmlBeanMap;
	}

	public static void main(String[] args) {
		parseXml();
	}

	public static void parseXml() {
		System.out.println("222222222222222222222");
		SAXBuilder builder = new SAXBuilder();
		Document document = null;
		try {
			String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
			String fileName = "struts-config.xml";
			document = builder.build(path + fileName);
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Element root = document.getRootElement();
		Element actionMapping = root.getChild("action-mapping");
		List<Element> actions = actionMapping.getChildren();

		ConfigBean xmlBean = new ConfigBean();
		for (Element action : actions) {
			String name = action.getAttributeValue("name");
			String actionClass = action.getAttributeValue("class");
			String path = action.getAttributeValue("path");
			xmlBean.setName(name);
			xmlBean.setActionClass(actionClass);
			List<Element> results = action.getChildren();
			Map<String, String> resultMap = new HashMap<String, String>();
			xmlBean.setMap(resultMap);
			for (Element result : results) {
				String resultName = result.getAttributeValue("name");
				String resultValue = result.getText();
				resultMap.put(resultName, resultValue);
			}
			Element formbean = root.getChild("formbean");
			List<Element> forms = formbean.getChildren();
			for (Element form : forms) {
				if (form.getAttributeValue("name").equals(name)) {
					String formClass = form.getAttributeValue("class");
					xmlBean.setFormClass(formClass);
					break;
				}
			}
			System.out.println(xmlBean);
			xmlBeanMap.put(path, xmlBean);
		}

	}

}
